package mgodb

import (
	"jgt-oper/src/model"
	"jgt-oper/src/schema"
	"jgt-oper/src/service/mongo"
	"jgt-oper/src/util"

	"github.com/facebookgo/inject"
	"github.com/globalsign/mgo"
	"github.com/globalsign/mgo/bson"
	"github.com/pkg/errors"
)

// 认证用户管理表名
const cAuthUser = "auth_user"

// AuthUser 认证用户管理
type AuthUser struct {
	DB *mongo.DB
}

// Init 初始化
func (a *AuthUser) Init(g *inject.Graph, db *mongo.DB) {
	a.DB = db

	var val model.IAuthUser = a
	g.Provide(&inject.Object{Value: val, Name: "IAuthUser"})
}

// Get 获取用户信息
func (a *AuthUser) Get(recordID string) (*schema.AuthUser, error) {
	var user schema.AuthUser
	err := a.DB.C(cAuthUser, func(c *mgo.Collection) error {
		return c.Find(bson.M{"_id": recordID}).One(&user)
	})
	if err != nil {
		if err == mgo.ErrNotFound {
			return nil, nil
		}
		return nil, errors.Wrapf(err, "精确查询数据发生错误")
	}
	return &user, nil
}

// Update 更新用户信息
func (a *AuthUser) Update(recordID string, info map[string]interface{}) error {
	err := a.DB.C(cAuthUser, func(c *mgo.Collection) error {
		return c.Update(bson.M{"_id": recordID}, bson.M{"$set": info})
	})
	if err != nil {
		return errors.Wrapf(err, "更新数据发生错误")
	}
	return nil
}

// QueryPageByTel 根据电话查询
func (a *AuthUser) QueryPageByTel(tel string, pageIndex, pageSize uint) (int64, []*schema.AuthUser, error) {
	var (
		items []*schema.AuthUser
		query = bson.M{"tel": bson.M{
			"$regex": util.TranSearch(tel),
		}}
		err   error
		total int64
	)
	err = a.DB.C(cAuthUser, func(c *mgo.Collection) error {
		n, err := c.Find(query).Count()
		if err != nil {
			return err
		}
		total = int64(n)
		if total == 0 {
			return nil
		}

		return c.Find(query).Sort("-_id").Skip(int((pageIndex - 1) * pageSize)).Limit(int(pageSize)).All(&items)

	})
	if err != nil {
		return 0, nil, errors.Wrapf(err, "分页查询数据发生错误")
	}
	return total, items, nil

}

// Search 搜索数据
func (a *AuthUser) Search(search string, count int) ([]*schema.AuthUser, error) {
	query := bson.M{
		"deleted": 0,
	}

	query["tel"] = bson.M{"$regex": util.TranSearch(search)}

	var items []*schema.AuthUser
	err := a.DB.C(cAuthUser, func(c *mgo.Collection) error {

		return c.Find(query).Sort("-_id").Limit(count).All(&items)
	})
	if err != nil {
		return nil, errors.Wrapf(err, "模糊查询数据发生错误")
	}

	return items, nil
}
